#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "func.h"
#include "proto.h"

void	w2f(const char *fname, uint8_t *in, int len)
{
	FILE	*fp;

	fp = fopen(fname, "w");
	if(fp)
	{
		fwrite(in, 1, len, fp);
		fclose(fp);
	}
}

void	gen_warn(FILE *fp)
{
	fprintf(fp, "/*\n"); 
	fprintf(fp, " *\tWARN  :  THIS FRONTEND CODE IS AUTO GENERATE, ALL RIGHTS RESERVED.\n");
	fprintf(fp, " *\tAUTHOR:  ZhaoChunPing\n");
	fprintf(fp, " *\tEMAIL :  forxy@126.com\n");
	fprintf(fp, " *\tDATE  :  2022.1\n");
	fprintf(fp, " */\n\n");

	fprintf(fp, "#include <stdint.h>\n");
	fprintf(fp, "#include \"pkcs11.h\"\n");
	fprintf(fp, "#include \"session.h\"\n");
	fprintf(fp, "#include \"auto_cmd.h\"\n\n");
	fprintf(fp, "pkcs11fun g_function[256];\n");
	fprintf(fp, "\n");
}

int	main(int argc, char *argv[])
{
	int	num, i, ret;
	FILE	*fp;
	char	buf[512] = {0};
	func_t *out, *cur;

	if(argc != 3)
	{
		printf("usage: gen_table func.proto auto_table.c\n");
		return -1;
	}

	ret = proto_load(argv[1], &out, &num);
	if(ret != 0) {
		printf("proto_load %s failed.\n", argv[1]);
		return -1;
	}
	fp = fopen(argv[2], "w");
	if(fp == NULL) {
		printf("open %s failed.\n", argv[2]);
		return -1;
	}
	gen_warn(fp);

	for(i = 0; i < num; i++)
	{
		cur = out + i;
		fprintf(fp, "extern void %s_backend(void *ctx, uint8_t *in, int inlen, uint8_t *out, int *outlen);\n", cur->name);
	}
	fprintf(fp, "\n");

	fprintf(fp, "void\tfunction_talble_init()\n{");
	for(i = 0; i < num; i++)
	{
		cur = out + i;

		memset(buf, 0, 512);
		sprintf(buf, "CMD_%s", cur->name);
		fprintf(fp, "\tg_function[%s] = %s_backend;\n", buf, cur->name);
		fflush(fp);
	}
	fprintf(fp, "}");
	fclose(fp);
	return 0;
}
